import 'package:hi_net/http/core/hi_net_adapter.dart';
import 'package:hi_net/http/core/hi_net_error.dart';
import 'package:hi_net/http/core/adapter/mock_adapter.dart';
import 'package:hi_net/http/request/base_request.dart';

import 'adapter/dio_adapter.dart';

///1.支持网络库插拔设计，且不干扰业务层
///2.基于配置请求请求，简洁易用
///3.Adapter设计，扩展性强
///4.统一异常和返回处理
class HiNet {
  HiNet._internal();

  static HiNet? _instance;

  static HiNet get getInstance {
    _instance ??= HiNet._internal();
    return _instance!;
  }

  Future fire(BaseRequest request) async {
    HiNetResponse? response;
    var error;
    try {
      response = await _send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      print("HiNet HiNetError:${e.message}");
    } catch (e) {
      // 其他错误
      error = e;
      print("HiNet OtherError:$e");
    }

    if (response == null) {
      print("HiNet error:$error");
    }
    var result = response?.data;
    print("HiNet result:$result");

    var status = response?.statusCode ?? 0;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw HiNetError(status, result.toString(), data: result);
    }
  }

  Future<dynamic> _send<T>(BaseRequest request) {
    print("url:${request.url()}");
    /// 使用mock发送请求
    /// HiNetAdapter adapter = MockAdapter();
    /// 使用dio发送请求
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }
}
